package top.mcwebsite.playandroid.business.project.impl.vm

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.paging.cachedIn
import top.mcwebsite.playandroid.business.project.impl.api.ProjectApiService
import top.mcwebsite.playandroid.business.project.impl.model.ProjectModel
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.common.network.model.ApiResult
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class ProjectViewModel : BaseViewModel<ProjectIntent, ProjectUiState, ProjectUiEffect>(ProjectUiState()) {

    private val projectApiService = ServiceManager.getService<NetworkService>()
        .createApi<ProjectApiService>()

    private val pager = Pager(PagingConfig(pageSize = 10)) {
        ProjectPagingSource()
    }

    val pagerFlow = pager.flow.cachedIn(viewModelScope)

    override fun handleIntent(intent: ProjectIntent) {
        when (intent) {
            is ProjectIntent.ClickItemIntent -> {
                sendUiEffect(ProjectUiEffect.NavigationToDetailPageUiEffect(intent.projectModel))
            }
        }
    }

    private inner class ProjectPagingSource : PagingSource<Int, ProjectModel>() {
        override fun getRefreshKey(state: PagingState<Int, ProjectModel>): Int? {
            return null
        }

        override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ProjectModel> {
            return try {
                val nextPageNumber = params.key ?: 0
                when (val result = projectApiService.projects(nextPageNumber)) {
                    is ApiResult.Success -> {
                        LoadResult.Page(
                            data = result.data.data?.datas ?: emptyList(),
                            prevKey = if (nextPageNumber == 0) null else nextPageNumber - 1,
                            nextKey = if (result.data.data?.over == true) null else nextPageNumber + 1
                        )
                    }
                    is ApiResult.Failure -> {
                        LoadResult.Error(result.cause)
                    }
                }
            } catch (e: Exception) {
                return LoadResult.Error(e)
            }
        }

    }
}